from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404

from .models import ExcelFormat
from .models import ColumnFormat

import json
import framework.storage.db as db


# Create your views here.

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")


def excel(request, excel_format_id, json_data_id):
    excel_format = get_object_or_404(ExcelFormat, key=excel_format_id)
    #excel_format = ExcelFormat.objects.get(key=excel_format_id)
    assert isinstance(excel_format, object)
    columns = ColumnFormat.objects.filter(excel=excel_format)

    columns_javascript = []
    for column in columns:
        columns_javascript.append(column.javascript)

    print(columns_javascript)
    javascript_str = '[' + ', '.join(columns_javascript) + ']'

    return render(request, 'easyui/excel.html', {
        'title': excel_format_id + ' - ' + json_data_id, 'columns_javascript': javascript_str, 'json_data_id': json_data_id, })


def update(request, json_data_id):
    if request.method == 'POST':
        db.sync(json_data_id, json.loads(request.body.decode())['rows'])
        return HttpResponse('{"success":true}', content_type="application/json")
    return HttpResponse('', content_type="application/json")


def data(request, json_data_id):
    if request.method == 'POST':
        if 'page' in request.POST.keys() and 'rows' in request.POST.keys():
            json_data = db.read_page_json(json_data_id, int(request.POST['page']), int(request.POST['rows']))
        else:
            json_data = db.read_json(json_data_id)

        return HttpResponse(json_data, content_type="application/json")
    return HttpResponse('', content_type="application/json")
